import Vue from 'vue'
import Router from 'vue-router'
// 导入登录组件
import Login from './components/Login.vue'
// 主页组件
import Home from './components/Home.vue'
// 欢迎组件
import Welcome from './components/Welcome.vue'
// 用户列表展示组件
import Users from './components/user/Users.vue'
// 用户管理组件
import Roles from './components/power/Roles.vue'
// 权限管理组件
import Rights from './components/power/Rights.vue'
// 商品管理组件
import Cate from './components/goods/Cate.vue'
// 分类参数组件
import Params from './components/goods/Params.vue'
// 商品列表组件
import List from './components/goods/List.vue'
// 添加商品页面
import Add from './components/goods/Add.vue'
// 订单管理功能
import Order from './components/order/Order.vue'

Vue.use(Router)

const router = new Router({
  // 定义路由规则 路径为 login时渲染登录组件 Login
  routes: [
    { path: '/', redirect: '/login' },
    { path: '/login', component: Login },
    {
      path: '/home',
      component: Home,
      redirect: '/welcome',
      children: [
        { path: '/welcome', component: Welcome },
        { path: '/users', component: Users },
        { path: '/rights', component: Rights },
        { path: '/roles', component: Roles },
        { path: '/categories', component: Cate },
        { path: '/params', component: Params },
        { path: '/goods', component: List },
        { path: '/goods/add', component: Add },
        { path: '/orders', component: Order }
      ]
    }
  ]
})
// 挂载路由守卫
router.beforeEach((to, from, next) => {
  // to 将访问的路径
  // from 从哪个路径跳转过来
  // next是一个函数 放行
  // next() next('/login')强制跳转
  if (to.path === '/login') return next() // 用户访问的是 登录页面之间放行
  const tokenStr = window.sessionStorage.getItem('token') // 浏览器中获取sessionStorage的token
  if (!tokenStr) return next('/login')// 如果没有token值就是非登录的状态  强制到登录页面
  next() // 有token值代表登录了 可以放行
})
export default router
